<?php

namespace App\Http\Controllers;

use App\Models\MemberGroup;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;

class ShopController extends Controller
{
    private $wxUser;
    protected $user;
    protected $active = 'index';
    protected $memberGroup;
    public function __construct()
    {
        $this->wxUser = session('wechat.oauth_user');
        $this->verifyReader();
        $this->wxLogin();
        $this->memberGroup = MemberGroup::orderBy('requireIntegral', 'asc')->get()->keyBy('id');
        View::share(['USER' => $this->user, 'USER_GROUP' => $this->memberGroup]);
    }

    private function verifyReader()
    {
        if(empty($this->wxUser))
            dd('error');
    }

    private function wxLogin()
    {
        $this->user = Auth::user();
        if(!$this->user || $this->user->openID != $this->wxUser->id)
        {
            Auth::logout();
            $wx = User::where('openID', $this->wxUser->id)->first();
            if($wx)
            {
                $wx->sex = isset($this->wxUser->original->sex) ? $this->wxUser->original->sex : 0;
                $wx->save();
                Auth::login($wx, true);
            }else{
                $createData = [
                    'type'      =>  'member',
                    'lv'        =>  0,
                    'sex'       =>  isset($this->wxUser->original->sex) ? $this->wxUser->original->sex : 0,
                    'integral'  =>  0,
                    'signNum'   =>  0,
                    'openID'    =>  $this->wxUser->id,
                    'name'      =>  $this->wxUser->name.date('Ymd', time()),
                    'realName'  =>  $this->wxUser->nickname,
                    'thumb'     =>  $this->wxUser->avatar,
                    'groupID'   =>  10001
                ];
                Auth::login($this->create($createData));
            }
            $this->user = Auth::user();
        }
    }

    protected function create(array $data)
    {
        return User::create($data);
    }
}
